package com.example.unitorder;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.TreeMap;

@SpringBootApplication
@RestController
public class UnitorderApplication {
	@Value("${custom.unitorder}")
	private String unitorder;
	@Autowired
	private ObjectMapper objectMapper;
	@Autowired
	private RestTemplate restTemplate;

	@Bean
	public RestTemplate restTemplate() {
		RestTemplate restTemplate = new RestTemplate();
		return restTemplate;
	}

	/**
	 * 手机扫码支付
	 *
	 * @param pay
	 * @return
	 */
	@RequestMapping(value = "scanpay", method = RequestMethod.POST)
	public Object unitorder(@RequestBody TreeMap<String, Object> pay, HttpServletRequest httpServletRequest) throws IOException {
		StringBuffer stringBuffer = new StringBuffer();
		for (Map.Entry<String, Object> entry : pay.entrySet()) {
			stringBuffer.append("&" + entry.getKey() + "=" + entry.getValue());
		}
		String uri = stringBuffer.substring(1);
		String sign = DigestUtils.md5DigestAsHex(uri.getBytes()).toUpperCase();
		pay.put("sign", sign);
		uri += "&" + "sign" + "=" + sign;
		HttpPost httppost = new HttpPost(
				unitorder + "scanpay?" + uri);
		CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
		HttpResponse httpResponse = closeableHttpClient.execute(httppost);
		if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			HttpEntity httpEntity = httpResponse.getEntity();
			InputStream content = httpEntity.getContent();
			Object o = objectMapper.readValue(content, Object.class);
			return o;
		} else {
			return null;
		}

	}


	public static void main(String[] args) {
		SpringApplication.run(UnitorderApplication.class, args);
	}
}
